/**
 * 本地存储模块
 * 封装微信存储API，模拟数据库功能
 */

// 基础存储操作
function get(key) {
  try {
    return wx.getStorageSync(key);
  } catch (e) {
    console.error('[Storage] 获取数据失败:', key, e);
    return null;
  }
}

function set(key, value) {
  try {
    wx.setStorageSync(key, value);
    return true;
  } catch (e) {
    console.error('[Storage] 存储数据失败:', key, e);
    return false;
  }
}

function remove(key) {
  try {
    wx.removeStorageSync(key);
    return true;
  } catch (e) {
    console.error('[Storage] 删除数据失败:', key, e);
    return false;
  }
}

function clear() {
  try {
    wx.clearStorageSync();
    return true;
  } catch (e) {
    console.error('[Storage] 清空存储失败:', e);
    return false;
  }
}

// 数据表操作封装
const db = {
  /**
   * 用户表操作
   */
  user: {
    // 获取当前用户信息
    getCurrentUser: () => get('currentUser'),
    // 设置当前用户信息
    setCurrentUser: (userData) => set('currentUser', userData),
    // 清除当前用户信息(登出)
    clearCurrentUser: () => remove('currentUser'),
    // 检查用户是否已登录
    isLoggedIn: () => !!get('currentUser'),
    // 获取登录令牌
    getToken: () => get('userToken'),
    // 设置登录令牌
    setToken: (token) => set('userToken', token),
    // 清除登录令牌
    clearToken: () => remove('userToken')
  },

  /**
   * 用户医疗病史表操作
   */
  medicalHistory: {
    // 获取所有病史记录
    getAll: () => get('medicalHistory') || [],
    // 添加病史记录
    add: (record) => {
      const records = get('medicalHistory') || [];
      const newRecord = {
        ...record,
        id: Date.now().toString(),
        createdAt: new Date().toISOString()
      };
      records.unshift(newRecord);
      set('medicalHistory', records);
      return newRecord;
    },
    // 更新病史记录
    update: (id, data) => {
      const records = get('medicalHistory') || [];
      const index = records.findIndex(r => r.id === id);
      
      if (index === -1) return null;
      
      records[index] = {
        ...records[index],
        ...data,
        updatedAt: new Date().toISOString()
      };
      
      set('medicalHistory', records);
      return records[index];
    },
    // 删除病史记录
    delete: (id) => {
      const records = get('medicalHistory') || [];
      const newRecords = records.filter(r => r.id !== id);
      
      if (newRecords.length === records.length) return false;
      
      set('medicalHistory', newRecords);
      return true;
    },
    // 获取单条病史记录
    getById: (id) => {
      const records = get('medicalHistory') || [];
      return records.find(r => r.id === id) || null;
    }
  },

  /**
   * 健康目标表操作
   */
  healthTargets: {
    // 获取所有健康目标
    getAll: () => get('healthTargets') || [],
    // 添加健康目标
    add: (target) => {
      const targets = get('healthTargets') || [];
      const newTarget = {
        ...target,
        id: Date.now().toString(),
        createdAt: new Date().toISOString(),
        progress: 0,
        status: 'active'
      };
      targets.unshift(newTarget);
      set('healthTargets', targets);
      return newTarget;
    },
    // 更新健康目标
    update: (id, data) => {
      const targets = get('healthTargets') || [];
      const index = targets.findIndex(t => t.id === id);
      
      if (index === -1) return null;
      
      targets[index] = {
        ...targets[index],
        ...data,
        updatedAt: new Date().toISOString()
      };
      
      set('healthTargets', targets);
      return targets[index];
    },
    // 删除健康目标
    delete: (id) => {
      const targets = get('healthTargets') || [];
      const newTargets = targets.filter(t => t.id !== id);
      
      if (newTargets.length === targets.length) return false;
      
      set('healthTargets', newTargets);
      return true;
    },
    // 获取单条健康目标
    getById: (id) => {
      const targets = get('healthTargets') || [];
      return targets.find(t => t.id === id) || null;
    }
  }
};

// 导出模块
module.exports = {
  get,
  set,
  remove,
  clear,
  db
}; 